/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO;

import racesuitefx.entities.Race;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author Wolfgang
 */
public class RaceDAO extends AbstractDAO<Race> {

    public RaceDAO(Class<Race> entityClass) {
        super(entityClass);
    }

    public RaceDAO() {
        super(Race.class);
    }

    @Override
    protected EntityManager getEntityManager() {
        return Persistence.createEntityManagerFactory("ModelsPU").createEntityManager();

    }

    public boolean startRace(Race r) {
        boolean retVal;
        Query q = this.getEntityManager().createNamedQuery("Race.findByActive");
        q.setParameter("active", "1");
        try {
            Race found = (Race) q.getSingleResult();
            return false;
        } catch (NoResultException ex) {
            retVal = true;
        }
        r.setActive("1");
        this.edit(r);
        return true;
    }

    public void stopRace(Race r) {
        r.setActive("0");
        this.edit(r);
    }

    public List<RaceResult> getResults(int raceId) {
        EntityManager manager = this.getEntityManager();
        String sql = "select count(lap.time) as loopCount, "
                + " time_to_sec(max(lap.time)) - time_to_sec(min(lap.time)) as elapsedTime,"
                + " lap.tagId as tagId, "
                + " starter.startNumber as startNumber, "
                + " starter.firstName as firstName , starter.lastName as lastName "
                + " from lap, starter "
                + "where lap.raceId = ? "
                + "  and lap.tagId = starter.tagId "
                + "  and lap.raceId = starter.raceId"
                + " group by lap.tagId order by count(lap.time) desc ,time_to_sec(max(lap.time)) - time_to_sec(min(lap.time)) asc" ;
        Query q = manager.createNativeQuery(sql);
        q.setParameter(1,raceId);
        List<RaceResult> resultList = new ArrayList<RaceResult>();
        List<Object> result = q.getResultList();
        for (Iterator iterator = result.iterator(); iterator.hasNext();) {
            Object[] r = (Object[]) iterator.next();
            resultList.add(new RaceResult(((Long)r[0]), ((Long)r[1]), ((String)r[2]),((Integer)r[3]), ((String)r[4]), ((String)r[5])));
        }
        return resultList;
    }

}
